import React, { useRef, useState } from 'react';
import { FileDoneOutlined, DeleteOutlined, FileAddOutlined } from '@ant-design/icons';
import { Button, message, Tag } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { request } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import { Avatar, Modal } from 'antd';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import { useAccess, Access } from 'umi';

import InserUserComponent from './InserUserComponent';
import UpdateUserComponent from './UpdateUserComponent';
import SubmitDataCpmponent from './SubmitDataCpmponent';
import { api } from '@/global';
type UserTableList = {
  id: string;
  phone: string;
  name: string;
  sex: string;
  email: string;
  statu: number;
  dept: string;
  role: string;
  avatar: string;
  num: string;
  professional: string;
};

type deptTyp = {
  id: string;
  deptName: string;
};

type conditionType = {
  id: string;
  statu: string;
};

type roleType = {
  id: string;
  roleName: string;
};

type professionalType = {
  id: string;
  professionalName: string;
};

export default () => {
  const [usreName, SetUserName] = useState<string>();
  const actionRef = useRef<ActionType>();
  const access = useAccess();
  function reloadPage() {
    actionRef.current?.reload();
  }

  const myColums: ProColumns<UserTableList>[] = [
    {
      dataIndex: 'index',
      title: '序列',
      valueType: 'indexBorder',
      width: 60,
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      width: 100,
      search: false,

      onFilter: true,
      align: 'center',

      render: (_, b) => {
        return <Avatar src={b.avatar}></Avatar>;
      },
    },
    {
      title: '姓名',
      dataIndex: 'name',
      tooltip: '模糊搜索名称',
      onFilter: true,
      align: 'center',
    },
    {
      title: '学号',
      onFilter: true,
      dataIndex: 'num',
    },

    {
      title: '性别',
      onFilter: true,
      dataIndex: 'sex',
      valueType: 'select',
      width: 50,
      valueEnum: {
        0: { text: '全部', status: '0' },
        1: { text: '男', status: 'man' },
        2: { text: '女', status: 'woman' },
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      search: false,
      onFilter: true,
    },
    {
      title: '所在系部',
      dataIndex: 'dept',
      valueType: 'select',
      onFilter: true,

      request: async () => {
        const deptData = await request(api.getAllCondition, {});
        const list: any[] = [];
        list.push({
          label: '全部',
          value: 0,
        });
        deptData.data.map((item: deptTyp) => {
          list.push({
            label: item.deptName,
            value: item.id,
          });
        });

        return list;
      },
    },
    {
      title: '所在专业',
      dataIndex: 'professional',

      request: async () => {
        const conditionData = await request(api.getSimpleProfessional, {});

        const list: any[] = [];
        list.push({
          label: '全部',
          value: 0,
        });
        conditionData.data.map((item: professionalType) => {
          list.push({
            label: item.professionalName,
            value: item.id,
          });
        });

        return list;
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
      valueType: 'select',
      onFilter: true,
      request: async () => {
        const conditionData = await request(api.getRoleList, {});

        const list: any[] = [];
        list.push({
          label: '全部',
          value: 0,
        });
        conditionData.data.map((item: roleType) => {
          list.push({
            label: item.roleName,
            value: item.id,
          });
        });

        return list;
      },
    },
    {
      title: '状态',
      dataIndex: 'statu',
      valueType: 'select',

      width: 80,
      onFilter: true,
      align: 'center',
      request: async () => {
        const conditionData = await request(api.getAllCondition, {});

        const list: any[] = [];
        list.push({
          label: '全部',
          value: 0,
        });
        conditionData.data.map((item: conditionType) => {
          list.push({
            label: item.statu,
            value: item.id,
          });
        });

        return list;
      },
      render: (_, b) => {
        let color: string = '';
        let code: string = '';
        if (b.statu === 1) {
          color = '#1abc9c';
          code = ' 可用 ';
        } else if (b.statu === 2) {
          color = '#e74c3c';
          code = '不可用 ';
        } else if (b.statu === 3) {
          color = '#70a1ff';
          code = '已毕业 ';
        } else {
          color = '#ced6e0';
          code = '其他情况';
        }

        return <Tag color={color}>{code}</Tag>;
      },
    },

    {
      title: '操作',
      onFilter: true,
      valueType: 'option',
      width: 200,
      align: 'center',
      render: (text, record, _, action) => [
        <Access key={'insert' + record.id} accessible={access.normalButtonFilter('USER:UPDATE')}>
          <UpdateUserComponent record={record} key="id" reloadPage={reloadPage} />
        </Access>,

        <Access key={'delete' + record.id} accessible={access.normalButtonFilter('USER:DELETE')}>
          <ModalForm
            key="id"
            title="删除用户"
            trigger={
              <Button type="danger">
                <DeleteOutlined />
                删除
              </Button>
            }
            submitter={{
              resetButtonProps: {
                type: 'dashed',
              },
            }}
            onVisibleChange={() => {
              SetUserName(record.name);
            }}
            onFinish={async (values) => {
              const result = await request(api.deleteUser, {
                method: 'POST',
                data: {
                  id: record.id,
                },
              });

              if (result.success) {
                message.info('删除成功');
                reloadPage();
                return true;
              } else {
                message.error('删除失败');
                return false;
              }
            }}
          >
            是否删除&nbsp;&nbsp;
            <span style={{ fontWeight: 900, fontSize: 25, color: '#3498db' }}>{usreName}</span>
            &nbsp;&nbsp;用户
          </ModalForm>
        </Access>,
      ],
    },
  ];
  return (
    <PageContainer
      waterMarkProps={{
        content: '山西工程技术学院',
      }}
      header={{
        title: '用户管理',
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '组织管理',
            },
            {
              path: '',
              breadcrumbName: '用户管理',
            },
          ],
        },
      }}
    >
      <ProTable<UserTableList>
        columns={myColums}
        actionRef={actionRef}
        request={async (params = {}, sort, filter) => {
          console.log(sort, filter);
          return request<{
            data: UserTableList[];
          }>(api.getUserList, {
            method: 'POST',

            data: {
              ...params,
            },
          });
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 20,
        }}
        dateFormatter="string"
        headerTitle="用户数据"
        toolBarRender={() => [
          <Access
            key="access1"
            accessible={access.normalButtonFilter('USER:INSERT')}
            fallback={<div></div>}
          >
            <InserUserComponent reloadPage={reloadPage} />
          </Access>,
          // <InserUserComponent key="access2" reloadPage={reloadPage} />,
          // <SubmitDataCpmponent />,
          // <Button key="button" icon={<FileDoneOutlined />} type="primary">
          //   导出数据
          // </Button>,
        ]}
      />
    </PageContainer>
  );
};
